#include "sqlexec.h"
#include <QDateTime>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

SqlExec::SqlExec(QObject *parent) : QObject(parent) {
  connect(this, &SqlExec::opened, this, &SqlExec::openedSlot);
}

void SqlExec::open(const QString &name) {
  db.reset(new QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL", name)));
  db->setHostName("127.0.0.1");
  db->setPort(3306);
  db->setUserName("daPeng");
  db->setPassword("123456789");
  db->setDatabaseName("project");
  bool isOpened = db->open();
  if (isOpened)
    emit this->opened();
  qDebug() << QString("DB '%1' connect %2")
                  .arg(name)
                  .arg(isOpened ? "success" : "failed");
}

bool SqlExec::add_device(int devID, const QString &name) {
  QString cmd =
      QString(
          "INSERT INTO data (deviceId ,deviceName, status) VALUES(%1, %2, %3);")
          .arg(devID)
          .arg(name)
          .arg(1);
  QSqlQuery query(*db);
  bool ok = query.exec(cmd);
  if (!ok) {
    qDebug() << query.lastError().text();
    return false;
  }
  return true;
}

bool SqlExec::update_dev_data(int devID, const QString &status) {
  QString cmd;
  //  cmd = QString("SELECT * FROM device WHERE ;");
  cmd = QString("UPDATE device SET status = '%1' WHERE deviceId = %2;")
            .arg(status)
            .arg(devID);
  QSqlQuery query(*db);
  bool ok = query.exec(cmd);
  if (!ok) {
    qDebug() << QString("%1>>%2").arg(__func__).arg(query.lastError().text());
    return false;
  }
  //  while (query.next()) {
  //    int id = query.value(0).toInt();
  //    double value = query.value(1).toDouble();
  //    QDateTime date = query.value(2).toDateTime();
  //    qDebug() << id;
  //    qDebug() << value;
  //  }
  return true;
}

void SqlExec::openedSlot() {}

bool SqlExec::add_dev_data(int devID, const QString &content) {
  QString cmd =
      QString(
          "INSERT INTO data (deviceId ,time, content) VALUES(%1, now(), '%2');")
          .arg(devID)
          .arg(content);
  QSqlQuery query(*db);
  bool ok = query.exec(cmd); //这里才是执行语句
  if (!ok) {
    qDebug() << QString("%1>>%2").arg(__func__).arg(query.lastError().text());
    return false;
  }
  return true;
}

/*
bool SqlExec::selValue1() {
  QString cmd;
  cmd = QString("SELECT * FROM CO2_history;");
  QSqlQuery query(*db);
  bool ok = query.exec(cmd); //这里才是执行语句
  if (!ok) {
    qDebug() << query.lastError().text();
    return false;
  }
  while (query.next()) {
    int id = query.value(0).toInt();
    double value = query.value(1).toDouble();
    QDateTime date = query.value(2).toDateTime();
    qDebug() << id;
    qDebug() << value;
  }
  return true;
}

bool SqlExec::delValue1(int id) {
  QString cmd;
  cmd = QString("delete from CO2_history where id=%1;")
            .arg(id); //如果是字符串要‘%1’这样写
  QSqlQuery query(*db);
  bool ok = query.exec(cmd); //这里才是执行语句
  if (!ok) {
    qDebug() << query.lastError().text();
    return false;
  }
  return true;
}
*/
